// pages/login/login.js
import {
  postNewLogin,
  getCode
} from '../../server/api/comapi';

Page({
  data: {
    check: false,
  },

  onShow() {
    this.getInLoginCode();
  },

  onUnload() {
    const app = getApp();
    app.globalData.nowPages = 0;
  },

  onBackPress(options) {
    wx.switchTab({
      url: "/pages/tabbar/home",
    });
  },

  openPage(e) {
    const type = e.currentTarget.dataset.type;
    console.log(`Opening page with type: ${type}`);
    // 根据 type 打开不同的页面或弹窗
  },

  getPhoneNumber(e) {
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      return wx.showToast({
        title: '登录失败，请重新登录！',
        icon: 'none',
      });
    }

    postNewLogin({
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      openId: getApp().globalData.openId,
      recommendId: wx.getStorageSync('recommendUserId').recommendUserId || 1,
    }).then(res => {
      wx.showLoading({
        title: "登录中~~~",
        mask: true,
      });

      const app = getApp();
      app.globalData.ifLogin = true;
      app.globalData.userId = res.data.data.userId;
      wx.setStorageSync('userInfo', res.data.data);

      if (res.data.data.phone) {
        app.globalData.token = res.data.data.token;
        app.globalData.ifLogin = true;
        wx.setStorageSync('token', app.globalData.token);
        wx.setStorageSync('newapp', '1');

        setTimeout(() => {
          wx.hideLoading();
          wx.navigateBack({
            delta: 1,
            success: () => {
              // 调用主页面的方法重置标志位
              const pages = getCurrentPages();
              const mainPage = pages.find(page => page.route === 'pages/index/index');
              if (mainPage) {
                mainPage.resetCodeProcessedFlag();
              }
            }
          });
        }, 1000);
      }
    }).catch(err => {
      wx.showToast({
        title: '取消登录！',
        icon: 'none',
      });
      setTimeout(() => {
        wx.switchTab({
          url: "/pages/home/home",
        });
      }, 1500);
      console.log(err, "取消登录");
    });
  },

  getInLoginCode() {
    wx.login({
      success: async loginRes => {
        try {
          const res = await getCode({
            code: loginRes.code,
            type: 1,
          });

          const app = getApp();
          app.globalData.openId = res.data.data.openId;
          wx.setStorageSync('openId', app.globalData.openId);

        } catch (err) {
          console.log(err, "getCode error");
        }
      },
      fail(error) {
        console.log(error, "login fail");
      },
    });
  },
});